package com.audaque.springboot.foshanupload.web.filter;

/**
 * @author zgb
 * @desc ...
 * @date 2022-02-02 01:19:58
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 删除url的.jsp
 *
 * @author zhaoheng
 */
@Component
@Slf4j
public class JspFilter implements Filter {



    @Override
    public void destroy() {

    }

    private void logThread() {
        log.debug("ThreadId:" + Thread.currentThread().getId());
        log.debug("ThreadName:" + Thread.currentThread().getName());
    }

    @SuppressWarnings("unchecked")
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rsp = (HttpServletResponse) response;
        String url0 = req.getRequestURI();
        String contextPath = req.getContextPath();
        log.debug("完整地址：" + url0);
        log.debug("返回当前页面所在的应用的名字：" + contextPath);
        logThread();
        // 获取请求地址
        String resourceUrl = ((HttpServletRequest) request).getRequestURI().substring(((HttpServletRequest) request).getContextPath().length());
        log.debug("resourceUrl：" + resourceUrl);
        String resourceUrlWithoutSuffix =null;
        String viewName=null;


        if (url0.endsWith(".jsp")) {
            //jsp是动态，不允许直接带.jsp后缀访问，得经过url映射jsp
            viewName = resourceUrl.replace(".jsp", "");
            //转发
            String viewPath="/"+viewName;
            req.getRequestDispatcher(viewPath).forward(req,rsp);
        }else{
            chain.doFilter(request, response);
            //放行后一定要return,否则有多个放行代码时会发起多个请求
            return;
        }



    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}
